package com.itheima.aliyunsmsspringbootstart.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.itheima.aliyunsmsspringbootstart.pojo.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;

/**
 * 发送短信服务
 * @author 郭文亮
 * @since 2021/11/22 19:59
 */
@Slf4j
public class AliyunSmsService {
    private static final String SEARCHSEQ = "\"Message\":\"OK\"";

    private String regionId;
    private String accessKeyId;
    private String accessKeySecret;
    private String domain;
    private String signName;
    private String templateCode;

    public AliyunSmsService(AliyunSmsProperties aliyunSmsProperties) {
        this.regionId = aliyunSmsProperties.getRegionId();
        this.accessKeyId = aliyunSmsProperties.getAccessKeyId();
        this.accessKeySecret = aliyunSmsProperties.getAccessKeySecret();
        this.domain = aliyunSmsProperties.getDomain();
        this.signName = aliyunSmsProperties.getSignName();
        this.templateCode = aliyunSmsProperties.getTemplateCode();
    }

    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.regionId, this.accessKeyId, this.accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);
        // 生成6位数字随机验证码
        String code = getCode();

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(domain);
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.regionId);
        // 目标手机号
        request.putQueryParameter("PhoneNumbers", mobile);
        // 签名名称
        request.putQueryParameter("SignName", this.signName);
        // 短信模板code
        request.putQueryParameter("TemplateCode", this.templateCode);
        // 模板中变量替换
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, SEARCHSEQ)) {
                return code;
            }
            log.info("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + mobile, e);
        }
        return null;
    }

    /**
     * 生成6位数字随机验证码
     *
     * @return code
     */
    private static String getCode() {
        // 随机数的位数为6位
        int length = 6;
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append((new Random().nextInt(10)));
        }
        return sb.toString();
    }
}
